<?php

namespace AuctionBack\Controller;

use AuctionCore\AntNest\Sms;
use AuctionCore\System\AuctionException;
use AuctionCore\Account\Back\EmployeeList;
use AuctionCore\Common\Page;
use AuctionCore\Common\Util;
use AuctionCore\Other\MobVerify;
use AuctionCore\Account\Back\Employee;
use AuctionCore\Account\Back\Group;
use AuctionCore\Account\Back\Department;

/**
 * 员工中心
 */
class EmpController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        //分公司
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
    }


    public function index()
    {
        $p = I('request.p/d', 1);
        $bc_city = I('request.bc_city');

        $search_key = $_REQUEST['search_key'];
        $search_key = ($search_key == '帐号、姓名、电话' ? '' : $search_key);
        $limit = 10;

        $emp_list = new EmployeeList();
        $where = "";
        if ($search_key) {
            $where .= " and (real_name='{$search_key}' or mobile='{$search_key}' or username='{$search_key}') ";
        }
        $branch_id = $this->user_info['branch_id'];
        if ($branch_id > 0) {
            $where .= " and branch_id = $branch_id";
        }
        if ($bc_city) {
            $where .= " and branch_id = $bc_city";
        }
        $emp_list->condition = ' where status in (0,1) ' . $where;
        $list = $emp_list->get($limit, $p);
        // echo M()->getlastsql();
        // dump($list);exit;
        $count = $emp_list->count();

        $page = new Page($count, $limit);
        $page_data = $page->page_data();
        //获取分组
        $g = new \AuctionCore\Account\Back\Group();
        $gl = $g->get_list('status=0');
        $groups = array();
        foreach ($gl as $g) {
            $groups[$g['id']] = $g['title'];
        }
        foreach ($list as $k => $item) {
            $emp_groups = Employee::get_emp_group($item['emp_id']);
            foreach ($emp_groups as $gk => $g) {
                $list[$k]['groups'] .= "<i>" . $groups[$g['id']] . "</i>";
            }
        }

        $store = c('STORE');
        $departs = Department::getList('id,pid,name');
        $this->assign('departs', $departs);
        $this->assign('store', $store);
        $this->assign('glist', $groups);
        $this->assign('p', $p);
        $this->assign('page_data', $page_data);
        $this->assign('list', $list);
        $this->assign('count', $count);
        $this->display();
    }

    //修改密码
    public function ch_pwd()
    {
        $this->display();
    }

    //修改密码提交
    public function ci_ch_pwd()
    {
        $user_info = $this->user_info;
        if (empty($user_info)) {
            $this->helpJsonResult(502, "操作无权限");
        }
        $old_pwd = I("post.old_pwd");
        if (empty($old_pwd)) {
            $this->helpJsonResult(401, "原密码不能为空");
        }
        $new_pwd = I("post.new_pwd");
        $check_new = preg_match('/^[_0-9a-z]{6,16}$/i', $new_pwd);
        if (!$check_new) {
            $this->helpJsonResult(402, "密码应为6-16位字母或数字");
        }
        $new_pwd2 = I("post.new_pwd2");
        if ($new_pwd !== $new_pwd2) {
            $this->helpJsonResult(403, "两次输入密码不一至");
        }
        $name = $user_info['username'];
        $Emp = new Employee($name);
        $user_info = $Emp->user_info();
        $check = $Emp->check_pwd($old_pwd);
        if (!$check) {
            $this->helpJsonResult(405, "原密码不正确请重新输入");
        }
        if ($user_info['passwd'] == md5($new_pwd)) {
            $this->helpJsonResult(405, "新密码不能和原密码一致，请重新输入");
        }
        $ok = $Emp->change_password($new_pwd);
        if (!$ok) {
            $this->helpJsonResult(500, "服务器错误，修改失败");
        }
        $this->helpJsonResult(200, "修改成功");
    }

    //添加员工保存
    public function ci_create_emp()
    {
        try {
            $user_info = array();
            $passwd = I('post.passwd', '');
            $username = I('post.username', '');
            $real_name = I('post.real_name', '');
            $mobile = I('post.mobile', '');
            if (!$passwd) {
                $this->helpJsonResult(500, "密码不能为空");
            }
            if (!$username) {
                $this->helpJsonResult(500, "用户名不能为空");
            }
            if (!$real_name) {
                $this->helpJsonResult(500, "真实姓名不能为空");
            }
            if (!$mobile) {
                $this->helpJsonResult(500, "手机号不能为空");
            }
            if (!validatePhone($mobile)) {
                $this->helpJsonResult(500, "请输入正确的手机号");
            }
            $is_mobile_exist = Employee::isPhoneExist($mobile);
            if (!empty($is_mobile_exist)) {
                $this->helpJsonResult(500, "手机号已存在");
            }
            $user_info = array();
            $user_info['username'] = $username;
            $user_info['passwd'] = $passwd;
            $user_info['real_name'] = $real_name;
            $user_info['depart_id'] = I('post.depart_id/d', 0);
            if (!$user_info['depart_id']) {
                AuctionException::make_throw('300012');
            }
            $user_info['email'] = I('post.email', '');
            $user_info['mobile'] = $mobile;
            // $user_info['sex'] = I('post.sex',0);
            // $user_info['avatar'] = I('post.avatar','');
            // $user_info['describe'] = I('post.describe','');
            // $user_info['status'] = I('post.status',1);
            // $user_info['province_id'] = I('post.province_id',2);
            // $user_info['store'] = I('post.province_id',1);;
            // $user_info['group_id'] = I('post.province_id',0);;

            $user_id = \AuctionCore\Account\Back\Employee::create_emp($user_info);

            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    public function edit()
    {
        $username = I('get.username', '');
        if (empty($username)) {
            $this->helpJsRedirect("用户名错误");
        }
        $bu = new Employee($username);
        $detail = $bu->user_info();
        $d = new Department($detail['depart_id']);
        $depart = $d->detail();
        $detail['depart_name'] = $depart['name'];
        $g = new \AuctionCore\Account\Back\Group();
        $gl = $g->get_list();
        $store = c('STORE');
        $departs = Department::getList('id,pid,name');
        $this->assign('departs', $departs);
        $this->assign('emp', $detail);
        $this->assign('store', $store);
        $this->assign('glist', $gl);
        $this->display();
    }

    public function ci_edit()
    {
        $emp_id = I("post.emp_id/d", 0);
        if ($emp_id < 1) {
            $this->helpJsonResult(400, '用户id有误');
        }
        $real_name = I("post.real_name");
        if (empty($real_name))
            $this->helpJsonResult(400, "真实姓名不能为空");
        $depart_id = I("post.depart_id");
        if ($depart_id < 1)
            $this->helpJsonResult(400, "请选择员工所属部门");
        $mobile = trim(I("post.mobile"));
        if (empty($mobile))
            $this->helpJsonResult(400, "手机号不能为空");
        if (!validatePhone($mobile))
            $this->helpJsonResult(400, "手机号不正确");
        $where = ['mobile' => $mobile, 'status' => ['gt', -1]];
        $find_emp = M("employee")->where($where)->find();
        if (!empty($find_emp) && $find_emp['emp_id'] != $emp_id)
            $this->helpJsonResult(400, "手机号已存在");
        $email = I("post.email");

        try {
            $bu = new Employee($emp_id);
            $ok = $bu->update([
                'real_name' => $real_name,
                'depart_id' => $depart_id,
                'mobile' => $mobile,
                'email' => $email,
            ]);

            if ($ok === false)
                $this->helpJsonResult(500, '保存失败');

            $this->helpJsonResult(200, '保存成功');

        } catch (AuctionException $e) {
            $this->helpJsonResult(500, $e->getMessage());
            exit;
        }
    }

    //操作员工
    public function ci_op()
    {
        try {
            $username = $_POST['username'];
            $bu = new \AuctionCore\Account\Back\Employee($username);
            if ($_POST['op_type'] == '1') {
                $bu->disable();
            } else if ($_POST['op_type'] == '-1') {
                $bu->del();
            } else if ($_POST['op_type'] === '0') {
                $bu->enable();
            } else {
                throw new AuctionException('操作非法！');
            }

            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    //员工登录
    public function login()
    {
        if ($this->user_info) {
            header('location:' . WEB_URL . 'Index');
        }
        $this->display();
    }


    //登录提交 
    public function ci_login()
    {
        $name = I('post.user_name', '', 'trim');
        $password = I('post.passwd');

        if (empty($name)) {
            $this->helpJsonResult(400, '用户名不能为空');
        }

        if (empty($password)) {
            $this->helpJsonResult(400, '密码不能为空');
        }

        if (APP_STATUS != 'dev' && APP_STATUS != 'test') {
            $auth_code = I('post.auth_code');
            if (empty($auth_code)) {
                $this->helpJsonResult(400, '验证码不能为空');
            }
        }
        try {
            $bu = new Employee($name);

            //密码正确
            $info = $bu->check_pwd($password);
            if ($info) {
                if (APP_STATUS != 'dev' && APP_STATUS != 'test') {
                    $Sms = new Sms();
                    $ret = $Sms->verify(21, $info['mobile'], $auth_code);
                    if (!$ret) {
                        $this->helpJsonResult(400, "验证码不正确");
                    }
                }
                if ($info['status'] == 1) {
                    throw new AuctionException('你的账户已冻结,请联系管理员！', 2);
                }
                if ($info['status'] == -1) {
                    throw new AuctionException('用户名或密码错！', 2);
                }
                //找到人员对应的分公司等信息
                $info = $bu->get_user_branch($info);
                if (!$info) {
                    throw new AuctionException('用户信息错误，请联系管理员', 2);
                }

                //更新互斥登录
                $ul = new \AuctionCore\Account\UniqLogin();
                $uniq_login_token = $ul->update($info['emp_id']);
                $info['uniq_login_token'] = $uniq_login_token;
                //记入登录日志
                if (isset($info['emp_id']))
                    \AuctionCore\Account\Back\EmpLoginLog::save($info['emp_id'], sha1($uniq_login_token), get_client_ip());

                $session_verify_key = sha1(C('DB_HOST') . $info['emp_id']);
                $info['ver_key'] = $session_verify_key;
                unset($info['passwd']);

                $sess_value = json_encode($info);
                session('user_info', $sess_value);
                //记住登录
                cookie('user_info', urlencode($sess_value), 86400 * 7);

                echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => $info));
                exit;
            } else {
                throw new AuctionException('用户名或密码错！', 2);
            }
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    //获取登录验证码
    public function getAuthCode()
    {
        $name = I('post.user_name');
        if (empty($name)) {
            $this->helpJsonResult(400, '用户名不能为空');
        }
        $password = I('post.password');
        if (empty($password) || $password == '密码：') {
            $this->helpJsonResult(400, '密码不能为空');
        }
        try {
            $bu = new Employee($name);
            $info = $bu->user_info();

            if (md5($password) != $info['passwd']) {
                $this->helpJsonResult(500, "用户名或密码错误");
            }

            $Sms = new Sms();
            $res = $Sms->codeSend(21, $info['mobile']);
            if (!$res) {
                $this->helpJsonResult(500, '发送验证码失败,请稍后再试');
            }
            $this->helpJsonResult(200, '发送成功,请注意查收');
        } catch (AuctionException $e) {
            $this->helpJsonResult($e->getCode(), $e->getMessage());
        }
    }

    //登出
    public function logout()
    {
        session('user_info', null);
        cookie('user_info', null, -3600);
        $this->redirect("Emp/login");
    }

    //分组管理
    public function group_list()
    {
        $g = new Group();
        $page = I("get.p/d", 1);
        $size = 10;

        $glist = $g->get_list($page, $size);
        $this->assign('glist', $glist);
        $this->display();
    }

    public function ci_group_op()
    {
        try {
            $group_id = I('post.group_id/d');
            $op_type = I('post.op_type');
            if (!$group_id) {
                throw new AuctionException("组id非法!");
            }

            $g = new Group();
            if ($op_type == '-1') {
                $empInfo = Employee::get_emp_by_group_or_store($group_id);
                if (empty($empInfo)) { //如果分组下有员工的话，就不能删除
                    $g->del($group_id);
                } else {
                    echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '该组下还有员工，不能删除', 'data' => ''));
                    exit;
                }
            } else if ($op_type === '0') {
                $g->enable($group_id);
            } else if ($op_type === '1') {
                $g->disable($group_id);
            } else {
                throw new AuctionException('操作非法!');
            }
            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    public function group_add()
    {
        $group_id = I('get.group_id');
        if ($group_id) {
            $g = new Group();
            $group = $g->info($group_id);
            $group['rule_id'] = explode(',', $group['rules']);
            $this->assign('group', $group);
        }

        $r = new  \AuctionCore\Account\Back\Rule();
        $rule_list = $r->get_list();

        $this->assign('rule_list', $rule_list);
        $this->display();
    }

    /**
     * 用户组编辑
     **/
    public function employee_group_edit()
    {
        $groupId = I('get.group_id');
        $employeeList = Employee::emp_branch_group(0, $groupId); //获取用户组下面的用户
        $groupInfo = Employee::getGroupByGroupId($groupId);

        $this->assign('group_info', $groupInfo);
        $this->assign('group_id', $groupId);
        $this->assign('emp_List', $employeeList);
        $this->display();
    }


    /**
     * 保存员工组关系
     */
    public function saveEmpGroupRelation()
    {
        $groupId = I('post.group_id');
        $delArr = I('post.del_arr');
        $addArr = I('post.add_arr');
        $employee = new Employee($this->user_info['emp_id']);

        M()->startTrans();
        foreach ($delArr as $key => $value) {
            $data = [
                'emp_id' => $value,
                'id' => $groupId,
            ];
            $result = $employee->delEmpGroupRelation($data);
            if (!$result) {
                M()->rollback();
                $this->helpJsonResult(422, '删除员工权限组关系失败!');
            }
        }

        $lastAddArr = [];
        foreach ($addArr as $key => $value) {
            $lastAddArr[] = [
                'emp_id' => $value,
                'id' => $groupId,
            ];
        }

        if (!empty($lastAddArr)) {
            $result = $employee->addEmpGroupRelation($lastAddArr);
            if ($result) {
                M()->commit();
                $this->helpJsonResult(200, '操作成功!');
            } else {
                M()->rollback();
                $this->helpJsonResult(422, '添加员工权限组关系失败!');
            }
        } else {
            M()->commit();
            $this->helpJsonResult(200, '操作成功!');
        }

    }


    /**
     * 搜索员工
     */
    public function searchEmp()
    {
        $search_key = trim(I('post.search_key', ''));
        $groupId = I('post.group_id');

        $addedEmpList = Employee::emp_branch_group(0, $groupId); //得到已经

        $emp_list = new EmployeeList();
        $where = "";
        if ($search_key) {
            $where .= " and (real_name='{$search_key}' or mobile='{$search_key}' or username='{$search_key}') ";
        }

        $emp_list->condition = ' where status in (0,1) ' . $where;
        $list = $emp_list->getAll();

        foreach ($list as $key => &$value) {
            $empId = $value['emp_id'];
            foreach ($addedEmpList as $k => $v) {
                $newEmpId = $v['emp_id'];
                if ($empId == $newEmpId) {
                    $value['is_add'] = true; //表示已经添加过了
                    break;
                }
            }
        }
        $this->helpJsonResult(200, '搜索成功!', $list);
    }

    public function ci_group_save()
    {
        try {
            $group = new Group();
            $group_id = I('post.group_id/d', 0);
            $title = I('post.title/s', '');

            if (empty($title)) {
                $this->helpJsonResult(400, "请输入组名!");
            }
            $rules = implode(',', I('post.rule_id'));
            if (empty($rules)) {
                $this->helpJsonResult(400, "请选择权限!");
            }
            $data = array();
            $data['rules'] = $rules;
            $data['title'] = $title;
            $data['remark'] = I('post.remark', '');
            if ($group_id) {
                $group->update($data, "id='{$group_id}'");
            } else {
                $gid = $group->create($data);
            }
            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => $gid));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }

    }

    public function ci_rule_save()
    {
        $name = I('post.name', '');
        if (empty($name)) {
            $this->helpJsonResult(400, "请输入权限标识");
        }
        $title = I('post.title', '');
        if (empty($title)) {
            $this->helpJsonResult(400, "请输入权限标题");
        }
        $data = array();
        $data['name'] = $name;
        $data['title'] = $title;
        $data['pid'] = I('post.pid/d', 0);
        try {
            $r = new \AuctionCore\Account\Back\Rule();
            $rule_id = $r->create($data);
            if (!intval($rule_id) > 0)
                throw new AuctionException('添加权限失败');

            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }

    }

    public function set_group()
    {
        $e = new Employee($_REQUEST['emp_id']);
        //$bu = new Employee($username);

        //$e->user_info()
        $gs = $e->get_groups();
        $mygroup = array();
        $addedGroup = []; //已经添加了的组
        foreach ($gs as $key => $row) {
            //array_push($mygroup, $row['group_id']);
            array_push($mygroup, $row);
            unset($row['emp_id']);
            unset($row['group_id']);
            array_push($addedGroup, $row);
        }
        $g = new Group();
        $all_glist = $g->get_list('');
        $userInfo = $e->user_info();


        $this->assign('user_info', $userInfo);
        $this->assign('all_grou_list', $all_glist);
        foreach ($all_glist as $key => $val) {
            if (in_array($val, $addedGroup)) { //去掉已经添加了的权限
                unset($all_glist[$key]);
            }
        }

        $this->assign('last_group_list', $all_glist); //未添加的权限
        $this->assign('mygroup', $mygroup);
        $this->display();
    }

    public function ci_set_group()
    {
        $emp_id = I('post.emp_id/d', 0);
        if ($emp_id < 1) {
            $this->helpJsonResult(400, "账号信息错误");
        }
        try {
            $e = new Employee($emp_id);
            $gs = $e->get_groups();
            $mygroup = array();
            foreach ($gs as $key => $row) {
                array_push($mygroup, $row['group_id']);
            }

            // $post_group_list = I('post.group_id');
            $add_group = I('post.add_arr');
            $del_group = I('post.del_arr');

            foreach ($add_group as $key => $group_id) {
                $e->set_group($group_id);
            }
            foreach ($del_group as $key => $group_id) {
                $e->exgraft_group($group_id);
            }

            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

    //充值密码
    public function restpwd()
    {
        try {
            $username = $_POST['username'];
            $bu = new \AuctionCore\Account\Back\Employee($username);
            $bu->restPwd();
            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
            exit;
        } catch (AuctionException $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
            exit;
        }
    }

}
//end class